﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NetDisk.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace NetDisk.Dtos
{
    public class CreateFileDto : IValidatableObject
    {
        [ModelBinder(Name = "parent_id")]
        [Exists]
        public int ParentId { get; set; }

        public string RelativePath { get; set; }
        public string Filename { get; set; }

        [Required(ErrorMessage = "上传文件不能为空")]
        public IFormFile File { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var db = validationContext.GetService(typeof(ApplicationDbContext)) as ApplicationDbContext;
            var createFileDto = validationContext.ObjectInstance as CreateFileDto;
            var parentId = createFileDto.ParentId == 0 ? null : createFileDto.ParentId as int?;

            var uploadFilePath = createFileDto.RelativePath.TrimEnd((createFileDto.Filename).ToCharArray());
            var parentIndex = db.DirIndexes.Where(di => di.DirId == parentId).FirstOrDefault();
            var fullPath = $"{parentIndex?.DirPath}{uploadFilePath}";

            var fileQuery = db.UploadFiles
               .Where(f => f.ParentId == parentId
                    && f.RealName == createFileDto.File.FileName
                    && f.IsDir == false);
            var file = fileQuery.FirstOrDefault();

            if (file != null)
            {
                yield return new ValidationResult($"{file.Id}|文件 {createFileDto.File.FileName} 已经存在, 不能重复上传.", new[] { nameof(Filename) });
            }
        }
    }
}
